#!/bin/bash
lines=121


echo "解压安装包"
if [ -d "./nodes" ]
then
rm -fr nodes
fi
tail -n +$lines "$0" > nodes.tar.gz
#xz -d nodes.tar.xz
tar -xvf nodes.tar.gz

echo "拷贝节点到ros2_ws/install"
if [ ! -d ~/ros2_ws/install/ ]
then
mkdir -p ~/ros2_ws/install/
fi

cp -fr ./nodes/install/* ~/ros2_ws/install/
echo "拷贝树"
if [ ! -d ~/ros2_ws/tree/ ]
then
mkdir -p ~/ros2_ws/tree/
fi
cp -fr ./nodes/tree/* ~/ros2_ws/tree/

echo "拷贝DDS2ROS"
if [ ! -d ~/ros2_ws/install/dds2ros/ ]
then
mkdir -p ~/ros2_ws/install/dds2ros/
fi
cp ./nodes/DDS2ROS ~/ros2_ws/install/dds2ros/
cp ./nodes/dds_profiles.xml ~/ros2_ws/install/dds2ros/

echo "拷贝启动脚本"
if [ ! -d "~/droneyee_fly/" ]
then
echo "创建脚本路径"
mkdir -p ~/droneyee_fly
fi
cp ./nodes/realfly_startup.sh ~/droneyee_fly/realfly_startup.sh
cp ./nodes/max_gpu_freq.sh ~/droneyee_fly/max_gpu_freq.sh
cp ./nodes/max_cpu_freq.sh ~/droneyee_fly/max_cpu_freq.sh

rm -fr nodes
rm nodes.tar.gz

addSource(){
src=$(grep -i "${1}" ~/.bashrc)
len=$(expr length "$src")
if [ $len -eq 0 ] 
then
echo "source ${1}" | tee -a ~/.bashrc
fi
}

vehiId=1
read -p "输入飞机id:" vehiId


if [ $vehiId -le 0 -o $vehiId -gt 254 ]

then
vehiId = 1
fi

preId="\"tgt_system\" default=\"1\""
#preId=$(grep -i "\"tgt_system\" default" ~/ros2_ws/install/mavros/share/mavros/launch/px4.launch)
echo "preId: ${preId}"
#newId=" <arg name=\"tgt_system\" default=\"${vehiId}\" />"
newId="\"tgt_system\" default=\"${vehiId}\""
echo "newId: ${newId}"
sed -i "s/${preId}/${newId}/g" ~/ros2_ws/install/mavros/share/mavros/launch/px4.launch
#sed -i "s/${preId}/${newId}/g" ~/ros2_ws/install/mavros/share/mavros/launch/px4.launch
#sed -i 's/"tgt_system" default="1"/"tgt_system" default="$vehiId"/g' ~/ros2_ws/install/mavros/share/mavros/launch/px4.launch
#添加localhost
addhost(){
hostInf=$(grep -i "ROS_LOCALHOST_ONLY" ${1})
len=$(expr length "$hostInf")
if [ $len -eq 0 ]
then
echo "增加ROS_LOCALHOST_ONLY"
echo "export ROS_LOCALHOST_ONLY=1" | sudo tee -a ${1} #~/.bashrc
fi
}

#更新domainid
updateDomainId(){
domainInf=$(grep -i "ROS_DOMAIN" ${1})
echo "domainInf: ${domainInf}"
newDomain="export ROS_DOMAIN_ID=${vehiId}"
len=$(expr length "$domainInf")
if [ $len -eq 0 ]

then
echo "增加ROS_DOMAIN_ID"
echo "${newDomain}" | sudo tee -a ${1} #~/.bashrc
else
echo "替换ROS_DOMAIN_ID"
sudo sed -i "s/${domainInf}/${newDomain}/g" ${1} # ~/.bashrc
fi
}

updateDomainId ~/.bashrc
updateDomainId /etc/environment
#updateDomainId /root/.bashrc
addhost ~/.bashrc
addhost /etc/environment
#addhost /root/.bashrc
#增加source
addSource "/opt/ros/foxy/setup.bash"
addSource "~/ros2_ws/install/setup.bash"

#echo "增加开机启动"
#gnome-terminal -x ~/droneyee_fly/realfly_noterminal_startup.sh

#rm nodes.tar.xz
echo "安装完成"
exit 0
